package com.service.business.support;

import com.service.dao.constants.ConfigConstants;
import com.service.business.base.constants.RedisKeyConstants;
import com.service.business.base.enums.SmsTypeEnum;
import com.service.business.base.service.ConfigService;
import com.service.core.exception.CommonException;
import com.service.dao.model.SysConfig;
import com.service.utility.common.PictureValidationCodeUtil;
import com.service.utility.common.UUIDUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

/**
 * <dl>
 * <dt>platform</dt>
 * <dd>Description:</dd>
 * <dd>Copyright: Copyright (C) 2015</dd>
 * <dd>Company: </dd>
 * <dd>CreateDate: 2019年05月12日</dd>
 * </dl>
 *
 * @author
 */
@Slf4j
@Component
public class VerifyCodeUtil {

    @Autowired
    private MemCache memCache;
    @Autowired
    private Environment environment;
    @Autowired
    private ConfigService configService;

    public void verifyTextVerifyCode(String account, String verifyCode, SmsTypeEnum codeType) {
        String code = memCache.get(RedisKeyConstants.VERIFY_CODE + codeType.getValue() + account);
        String defaultVerifyCode = "";
        SysConfig config = configService.getConfigByName(ConfigConstants.DEFAULT_MSG_CODE);
        if (!ObjectUtils.isEmpty(config) && StringUtils.isNotBlank(config.getConfValue())) {
            defaultVerifyCode = config.getConfValue();
        }
        log.info("账户<{}>校验验证码 get code:{},cacheCode:{},default code:{}", account, verifyCode, code, defaultVerifyCode);
        if (StringUtils.equals(verifyCode, defaultVerifyCode)) {
            return;
        }
        if (!StringUtils.equals(code, verifyCode)) {
            log.info("账户<{}>校验验证码 get code:{},cacheCode:{},default code:{},校验失败", account, verifyCode, code, defaultVerifyCode);
            throw new CommonException("验证码错误", "verify_code_invalid");
        }
    }

    public void verifyImageVerifyCode(String configConstants, String picCodeId, String picCode){
        if (configService.configValueIsValid(configConstants)) {
            String URL = environment.getProperty("project.kaptcha-service-base-url") + "/kaptcha/validate";
            try {
                PictureValidationCodeUtil.validatePictureValidationCode(URL, picCodeId, picCode, UUIDUtil.randomUUID());
            } catch (Exception e) {
                throw new CommonException("图片验证码错误", "register_fail_by_pic_code_fail");
            }
        }
    }

}
